package persistance;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import model.DataModel;

public class DataModelDAO {
	
	private static final String INSERT = "INSERT INTO 7ABIFS20112_06.testdaten(id, timestamp, userid, productid, orderid, amount) VALUES(null, ?, ?, ?, ?, ?)";
	private final Connection c;
	private PreparedStatement prepInsert;

	public DataModelDAO(Connection c) {
		this.c = c;
	}
	
	public void saveAll(List<DataModel> list) throws SQLException {
		
		for (DataModel dataModel : list) {
			try {
				if(save(dataModel) <= 0) {
					throw new SQLException("No data inserted!");
				}
			} catch (SQLException e) {
				e.printStackTrace();
				c.rollback();
			}
		}
		c.commit();
		
	}

	private int save(DataModel dataModel) throws SQLException {
		if(prepInsert == null) {
			prepInsert = c.prepareStatement(INSERT);
		}
		
		prepInsert.setTimestamp(1, new Timestamp(dataModel.getTimestamp().getTime()));
		prepInsert.setLong(2, dataModel.getUserID());
		prepInsert.setLong(3, dataModel.getProductID());
		prepInsert.setLong(4, dataModel.getOrderID());
		prepInsert.setInt(5, dataModel.getAmount());
		
		return prepInsert.executeUpdate();
		
		
	}
	
	

}
